﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Infrastructure.Dao;
using ServiceStack;
using SqlSugar;
using DormMS.IService;
using DormMS.Model;
using DormMS.Model.SearchModels;
using DormMS.Model.ViewModels;

namespace DormMS.Service
{
    public class SpecialTopicService : ISpecialTopicService
    {

        public List<SpecialTopicResponse> SpecialTopicManage(SpecialTopicSearchModel search, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Sqlable sable = Db.Sqlable().From<Activity_SpecialTopic>("");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" Name like @name ");
                }

                var pars = new { name = "%" + search.Keywords + "%" };
                total = sable.Count(pars);
                var list = sable.SelectToPageList<SpecialTopicResponse>("*", search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                if (list != null && list.Count > 0)
                {
                    list.ForEach(m =>
                    {
                        if (!m.TopicProducts.IsNullOrEmpty() && m.TopicProducts != "[]")
                        {
                            m.TopicProductList = Db.Queryable<Product>().In(w => w.Id, m.TopicProducts.FromJson<List<int>>()).Where(w => w.IsDisplay).ToList() ?? new List<Product>();
                        }
                    });
                }
                return list;
            }
        }


        public SpecialTopicResponse SpecialTopicEdit(int Id)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var response = new SpecialTopicResponse { TopicProductList = new List<Product>() };

                if (Id > 0)
                {
                    response = Db.Queryable<Activity_SpecialTopic>().SingleOrDefault(m => m.Id == Id).ConvertTo<SpecialTopicResponse>();

                    var productlist = new List<Product>();
                    if (!response.TopicProducts.IsNullOrEmpty() && response.TopicProducts != "[]")
                    {
                        var productids = response.TopicProducts.FromJson<List<int>>();
                        productids.ForEach(m =>
                        {
                            var product = Db.Queryable<Product>().SingleOrDefault(s => s.Id == m && s.IsDisplay);
                            if (product != null && product.Id > 0)
                            {
                                var speclist = Db.Queryable<Product_Spec>().Where(s => s.ProductSku == product.Sku && s.Stock - s.WaitSendStock > 0).ToList();
                                if (speclist != null && speclist.Count > 0)
                                {
                                    product.Price = speclist.Min(n => n.Price);
                                    product.MarketPrice = speclist.Max(n => n.MarketPrice);
                                    product.TotalStock = speclist.Sum(n => n.Stock - n.WaitSendStock);
                                    productlist.Add(product);
                                }
                            }
                        });
                    }
                    response.TopicProductList = productlist;
                }

                return response;
            }
        }


        public Result SpecialTopicEditSubmit(SpecialTopicResponse submitData, int currentUserId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                if (submitData == null)
                {
                    return Result.Failure("参数错误");
                }
                //if (submitData.TopicProductList == null || submitData.TopicProductList.Count == 0)
                //{
                //    return Result.Failure("未选择包含产品");
                //}

                var specialTopic = submitData.ConvertTo<Activity_SpecialTopic>();

                //var productlist = Db.Queryable<Product>().In(m => m.Id, submitData.TopicProductList.Select(s => s.Id).ToList()).Where(m => m.IsDisplay).ToList() ?? new List<Product>();
                //specialTopic.TopicProducts = productlist.Select(s => s.Id).ToList().ToJson();

                //新增
                if (specialTopic.Id == 0)
                {
                    specialTopic.AddUserId = currentUserId;
                    if (Db.Insert(specialTopic).ObjToInt() > 0)
                    {
                        return Result.Success();
                    }
                }
                //编辑
                else
                {
                    specialTopic.EditUserId = currentUserId;
                    specialTopic.EditTime = DateTime.Now;
                    if (Db.Update(specialTopic))
                    {
                        return Result.Success();
                    }
                }
                return Result.Failure("操作失败，请稍候再试");
            }
        }


        public Result DelTopic(int Id, int currentUserId)
        {
            using (var Db = DbConfig.GetInstance())
            {
                if (Id == 0)
                {
                    return Result.Failure("数据不存在");
                }

                Db.Update<Activity_SpecialTopic>(new { IsDeleted = true }, m => m.Id == Id);
                return Result.Success();
            }
        }


        #region WAP

        public List<Product> SpecialTopicProduct(int Skip, int Take, int topicId, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                var topic = Db.Queryable<Activity_SpecialTopic>().SingleOrDefault(m => m.Id == topicId);
                if (topic == null || topic.Id == 0 || topic.TopicProducts.IsNullOrEmpty() || topic.TopicProducts.FromJson<List<int>>().Count == 0)
                {
                    total = 0;
                    return new List<Product>();
                }

                total = Db.Queryable<Product>().In(m => m.Id, topic.TopicProducts.FromJson<List<int>>()).Where(m => m.IsDisplay).Count();
                var list = Db.Queryable<Product>().In(m => m.Id, topic.TopicProducts.FromJson<List<int>>()).Where(m => m.IsDisplay).OrderBy(" Sort Desc,Id Desc ").Skip(Skip).Take(Take).ToList();
                list.ForEach(m =>
                {
                    var speclist = Db.Queryable<Product_Spec>().Where(w => w.ProductSku == m.Sku && w.IsDeleted == false && w.Stock - w.WaitSendStock > 0).ToList() ?? new List<Product_Spec>();
                    if (speclist != null && speclist.Count > 0)
                    {
                        m.Price = speclist.Min(s => s.Price);
                        m.MarketPrice = speclist.Max(s => s.MarketPrice);
                    }
                });
                return list;
            }
        }



        #endregion


    }
}
